<template>
  <!-- SDK 加载中提示 -->
  <div v-if="isInitializing" class="loading-overlay">
    <div class="loading-content">
      <div class="loading-spinner"></div>
      <div class="loading-text">正在加载腾讯云 SDK...</div>
      <div class="loading-hint">首次加载可能需要几秒钟</div>
    </div>
  </div>

  <div class="container" :class="{ hidden: isInitializing }">
    <div class="header">
      <h1>🎥 高级本地混流预览系统</h1>
      <p>支持多个摄像头、多个屏幕分享，可拖拽调整位置、大小和层级</p>
    </div>

    <div class="content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 添加流按钮 -->
        <div class="control-panel">
          <div class="panel-title">➕ 添加流</div>
          <div class="button-group">
            <button class="btn btn-primary" @click="showCameraModal = true">
              📹 添加摄像头
            </button>
            <button class="btn btn-warning" @click="showScreenModal = true">
              🖥️ 添加屏幕分享
            </button>
          </div>
        </div>

        <!-- 混流配置 -->
        <div class="control-panel">
          <div class="panel-title">⚙️ 混流配置</div>
          <div class="form-group">
            <label>输出分辨率</label>
            <select v-model="resolution">
              <optgroup label="📱 竖屏（9:16）推荐">
                <option value="1080,1920">1080x1920 (1080p 竖屏) ✨</option>
                <option value="720,1280">720x1280 (720p 竖屏)</option>
                <option value="540,960">540x960 (540p 竖屏)</option>
              </optgroup>
              <optgroup label="🖥️ 横屏（16:9）">
                <option value="1920,1080">1920x1080 (1080p 横屏)</option>
                <option value="1280,720">1280x720 (720p 横屏)</option>
                <option value="960,540">960x540 (540p 横屏)</option>
              </optgroup>
            </select>
          </div>
          <div class="form-group">
            <label>帧率 (FPS)</label>
            <input type="number" v-model.number="framerate" min="5" max="30">
            <small>建议范围：5-30</small>
          </div>
          <button class="btn btn-info" @click="applyConfig">
            应用配置
          </button>
        </div>

        <!-- 推流配置 -->
        <div class="control-panel">
          <div class="panel-title">🚀 推流配置</div>
          <div class="form-group">
            <label>推流域名</label>
            <input type="text" v-model="pushConfig.domain" placeholder="push.example.com">
            <small>在腾讯云控制台获取推流域名</small>
          </div>
          <div class="form-group">
            <label>应用名称</label>
            <input type="text" v-model="pushConfig.appName" placeholder="live">
          </div>
          <div class="form-group">
            <label>流名称</label>
            <div style="display: flex; gap: 5px;">
              <input type="text" v-model="pushConfig.streamName" placeholder="stream_001" style="flex: 1;">
              <button class="btn btn-info btn-sm" @click="generateStreamName">随机生成</button>
            </div>
          </div>
          <div class="form-group">
            <label>推流密钥</label>
            <input type="password" v-model="pushConfig.key" placeholder="在控制台获取">
          </div>
          <div class="info-box" style="margin: 15px 0;">
            <strong>📍 推流地址：</strong><br>
            <code style="word-break: break-all; font-size: 10px;">
              {{ pushUrl || '请填写配置' }}
            </code>
          </div>
          <div class="button-group">
            <button 
              class="btn btn-success" 
              :disabled="!canPush || isPushing"
              @click="handleStartPush"
            >
              开始推流
            </button>
            <button 
              class="btn btn-danger" 
              :disabled="!isPushing"
              @click="handleStopPush"
            >
              停止推流
            </button>
          </div>
        </div>

        <div class="info-box">
          <strong>💡 操作提示：</strong><br>
          • 点击"添加"按钮添加流<br>
          • 拖拽彩色边框调整位置<br>
          • 拖拽右下角调整大小<br>
          • 📹 摄像头不能超出画布边界<br>
          • 🖥️ 屏幕共享可以移出画布
        </div>
      </div>

      <!-- 中间区域：预览画布 + 拉流播放器 -->
      <div class="middle-section">
        <!-- 预览画布 -->
        <div class="preview-section">
          <div class="preview-title">
            📺 实时预览画布 (<span>{{ canvasSize }}</span>)
          </div>
          <div 
            id="preview-canvas" 
            ref="previewCanvas"
            :style="canvasStyle"
          >
            <div id="local_video"></div>
            <div 
              v-if="streamCount === 0" 
              class="empty-hint"
            >
              <p style="font-size: 16px;">👆 点击左侧添加摄像头或屏幕分享</p>
              <p style="font-size: 14px; margin-top: 10px; opacity: 0.7;">
                流将显示在此画布上，可拖拽调整
              </p>
            </div>

            <!-- 流框 -->
            <div
              v-for="stream in Array.from(streams.values())"
              :key="stream.id"
              class="stream-box"
              :class="{ selected: selectedStreamId === stream.id }"
              :style="getStreamBoxStyle(stream)"
              @mousedown="onStreamMouseDown($event, stream.id)"
            >
              <div class="stream-box-header">
                <span class="name">{{ stream.name }}</span>
                <button class="close-btn" @click.stop="removeStreamHandler(stream.id)">×</button>
              </div>
              <div 
                class="resize-handle"
                @mousedown.stop="onResizeMouseDown($event, stream.id)"
              ></div>
            </div>
          </div>
        </div>

        <!-- 拉流播放器 -->
        <div class="preview-section">
          <div class="preview-title">
            📥 拉流播放器
            <span style="float: right; font-size: 14px; font-weight: normal;">
              状态: <span class="status-badge" :class="{ active: isPlaying }">
                {{ isPlaying ? '播放中' : '未播放' }}
              </span>
            </span>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
            <div class="form-group" style="margin-bottom: 0;">
              <label>流名称</label>
              <div style="display: flex; gap: 5px;">
                <input type="text" v-model="playConfig.streamName" placeholder="自动同步推流名" style="flex: 1;">
                <button class="btn btn-info btn-sm" @click="syncPlayStreamName">同步</button>
              </div>
            </div>
            <div class="form-group" style="margin-bottom: 0;">
              <label>播放协议</label>
              <select v-model="playConfig.protocol">
                <option value="webrtc">WebRTC (超低延迟)</option>
                <option value="flv">FLV (低延迟)</option>
                <option value="hls">HLS (兼容性好)</option>
              </select>
            </div>
          </div>

          <div style="background: white; padding: 10px; border-radius: 6px; margin-bottom: 15px;">
            <div style="font-size: 12px; color: #666; margin-bottom: 5px;">📍 播放地址：</div>
            <code style="font-size: 11px; color: #10b981; word-break: break-all;">
              {{ playUrl || '请填写配置' }}
            </code>
          </div>

          <div style="display: flex; gap: 10px; margin-bottom: 15px;">
            <button 
              class="btn btn-success" 
              :disabled="!canPlay || isPlaying"
              @click="handleStartPlay"
              style="flex: 1;"
            >
              ▶️ 开始播放
            </button>
            <button 
              class="btn btn-danger" 
              :disabled="!isPlaying"
              @click="handleStopPlay"
              style="flex: 1;"
            >
              ⏹️ 停止播放
            </button>
          </div>

          <div id="player-container" style="width: 100%; background: #000; border-radius: 8px; overflow: hidden; aspect-ratio: 16/9;">
            <video id="player-video" style="width: 100%; height: 100%; object-fit: contain;" playsinline></video>
          </div>
        </div>
      </div>

      <!-- 右侧面板：流列表 + 系统状态 -->
      <div class="right-panel">
        <!-- 系统状态 -->
        <div class="control-panel">
          <div class="panel-title">📊 系统状态</div>
          <div style="font-size: 13px; line-height: 2;">
            <div>混流状态: <span class="status-badge" :class="{ active: streamCount > 0 }">
              {{ streamCount > 0 ? '已激活' : '未激活' }}
            </span></div>
            <div>推流状态: <span class="status-badge" :class="{ active: isPushing }">
              {{ isPushing ? '推流中' : '未推流' }}
            </span></div>
            <div>混流尺寸: <span>{{ canvasSize }}</span></div>
            <div>缩放比例: <span>{{ avgScale }}x</span></div>
          </div>
        </div>

        <!-- 流列表 -->
        <div class="control-panel">
          <div class="panel-title">📋 流列表 ({{ streamCount }})</div>
          <small style="display: block; margin: -10px 0 10px 0; font-size: 11px; color: #888;">
            按层级排序（上层在前）
          </small>
          <div class="stream-list">
            <div v-if="streamCount === 0" style="text-align: center; color: #999; padding: 20px;">
              暂无流
            </div>
            <div
              v-for="stream in sortedStreams"
              :key="stream.id"
              class="stream-item"
              :class="{ selected: selectedStreamId === stream.id }"
              @click="selectStreamHandler(stream.id)"
            >
              <div class="stream-item-header">
                <div class="stream-item-title">
                  {{ stream.type === 'camera' ? '📹' : '🖥️' }} {{ stream.name }}
                </div>
                <div class="stream-item-badge">
                  {{ stream.type === 'camera' ? '摄像头' : '屏幕' }}
                </div>
              </div>
              <div class="stream-item-info">
                位置: {{ Math.round(stream.x) }}, {{ Math.round(stream.y) }} | 
                大小: {{ Math.round(stream.width) }}x{{ Math.round(stream.height) }}
              </div>
              <div class="stream-item-info">
                层级: <strong>{{ stream.zOrder }}</strong>
                <span style="color: #888; font-size: 11px;">(数值越大越在上层)</span>
              </div>
              <div class="stream-item-actions">
                <button 
                  class="btn btn-xs" 
                  style="background: #8b5cf6; color: white;" 
                  @click.stop="moveToTop(stream.id)"
                  title="将此流移到最上层"
                >
                  🔝
                </button>
                <button 
                  class="btn btn-xs" 
                  style="background: #3b82f6; color: white;" 
                  @click.stop="moveUp(stream.id)"
                  title="向上移动一层"
                >
                  ⬆️
                </button>
                <button 
                  class="btn btn-xs" 
                  style="background: #06b6d4; color: white;" 
                  @click.stop="moveDown(stream.id)"
                  title="向下移动一层"
                >
                  ⬇️
                </button>
                <button 
                  class="btn btn-danger btn-xs" 
                  @click.stop="removeStreamHandler(stream.id)"
                  title="删除此流"
                >
                  🗑️
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 对话框 -->
  <CameraModal
    v-model="showCameraModal"
    :canvas-width="canvasWidth"
    :canvas-height="canvasHeight"
    :stream-counter="streamCounter"
    @confirm="handleAddCamera"
  />

  <ScreenModal
    v-model="showScreenModal"
    :canvas-width="canvasWidth"
    :canvas-height="canvasHeight"
    :stream-counter="streamCounter"
    @confirm="handleAddScreen"
  />
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useLiveMixer } from '../composables/useLiveMixer'
import CameraModal from './CameraModal.vue'
import ScreenModal from './ScreenModal.vue'

// 使用 composable
const {
  streams,
  selectedStreamId,
  streamCounter,
  canvasWidth,
  canvasHeight,
  isPushing,
  scaleX,
  scaleY,
  isPlaying,
  streamCount,
  canvasSize,
  avgScale,
  init,
  updateMixingConfig,
  calculateScale,
  applyLayout,
  generatePushUrl,
  generatePlayUrl,
  addCamera,
  addScreen,
  removeStream,
  updateStream,
  startPush,
  stopPush,
  startPlay,
  stopPlay,
  isDragging,
  isResizing,
  dragStartX,
  dragStartY,
  dragStreamId
} = useLiveMixer()

// 本地状态
const showCameraModal = ref(false)
const showScreenModal = ref(false)
const resolution = ref('1280,720')
const framerate = ref(15)
const previewCanvas = ref(null)
const isInitializing = ref(true)

// 推流配置
const pushConfig = reactive({
  domain: '222038.push.tlivecloud.com',
  appName: 'live',
  streamName: '',
  key: '8ar3F6EKGehacZjAAXJY'
})

// 播放配置
const playConfig = reactive({
  domain: 'test.20ai30.com',
  appName: 'live',
  streamName: '',
  protocol: 'webrtc',
  key: '5ZWHzarfnccHyJxWFfM5'
})

// 计算属性
const pushUrl = computed(() => 
  generatePushUrl(pushConfig.domain, pushConfig.appName, pushConfig.streamName, pushConfig.key)
)

const playUrl = computed(() =>
  generatePlayUrl(playConfig.domain, playConfig.appName, playConfig.streamName, playConfig.protocol, playConfig.key)
)

const canPush = computed(() => streamCount.value > 0 && pushUrl.value !== '')

const canPlay = computed(() => playUrl.value !== '')

// 按层级排序的流列表（从高到低）
const sortedStreams = computed(() => {
  return Array.from(streams.values()).sort((a, b) => b.zOrder - a.zOrder)
})

const canvasStyle = computed(() => {
  const aspectRatio = canvasWidth.value / canvasHeight.value
  const isVertical = canvasHeight.value > canvasWidth.value
  
  return {
    width: '100%',
    background: '#1a1a1a',
    borderRadius: '8px',
    position: 'relative',
    overflow: 'hidden',
    aspectRatio: `${canvasWidth.value} / ${canvasHeight.value}`,
    maxHeight: isVertical ? '800px' : '600px',
    maxWidth: isVertical ? '400px' : '100%',
    margin: '0 auto'
  }
})

// 获取流框样式
const getStreamBoxStyle = (stream) => {
  const displayX = stream.x * scaleX.value
  const displayY = stream.y * scaleY.value
  const displayWidth = stream.width * scaleX.value
  const displayHeight = stream.height * scaleY.value

  return {
    left: `${displayX}px`,
    top: `${displayY}px`,
    width: `${displayWidth}px`,
    height: `${displayHeight}px`,
    zIndex: stream.zOrder
  }
}

// 方法
const applyConfig = () => {
  const [w, h] = resolution.value.split(',').map(Number)
  canvasWidth.value = w
  canvasHeight.value = h
  updateMixingConfig()
  
  nextTick(() => {
    calculateScale()
  })
}

const generateStreamName = () => {
  pushConfig.streamName = 'stream_' + Date.now()
}

const syncPlayStreamName = () => {
  if (!pushConfig.streamName) {
    alert('⚠️ 推流名称为空！请先设置推流名称。')
    return
  }
  playConfig.streamName = pushConfig.streamName
  alert(`✅ 已同步流名称：${pushConfig.streamName}`)
}

const handleAddCamera = async (config) => {
  try {
    await addCamera(config)
    console.log('摄像头添加成功')
  } catch (error) {
    console.error('添加摄像头失败:', error)
    alert('添加摄像头失败: ' + error.message)
  }
}

const handleAddScreen = async (config) => {
  try {
    await addScreen(config, config.sourceId)
    console.log('屏幕分享添加成功')
  } catch (error) {
    console.error('添加屏幕分享失败:', error)
    alert('添加屏幕分享失败: ' + error.message)
  }
}

const removeStreamHandler = (streamId) => {
  if (confirm('确定要删除这个流吗？')) {
    removeStream(streamId)
  }
}

const selectStreamHandler = (streamId) => {
  selectedStreamId.value = streamId
}

// 层级调整方法
const moveToTop = (streamId) => {
  const stream = streams.get(streamId)
  if (!stream) return

  // 找到当前最大的 zOrder
  const maxZOrder = Math.max(...Array.from(streams.values()).map(s => s.zOrder), 0)
  
  // 如果已经是最上层，不需要调整
  if (stream.zOrder === maxZOrder) {
    return
  }

  stream.zOrder = maxZOrder + 1
  applyLayout()
  
  console.log(`流 "${stream.name}" 已置顶，层级：${stream.zOrder}`)
}

const moveUp = (streamId) => {
  const stream = streams.get(streamId)
  if (!stream) return

  // 获取所有流并按 zOrder 排序
  const sortedStreams = Array.from(streams.values()).sort((a, b) => a.zOrder - b.zOrder)
  
  // 找到当前流的索引
  const currentIndex = sortedStreams.findIndex(s => s.id === streamId)
  
  // 如果已经是最上层，不能再上移
  if (currentIndex === sortedStreams.length - 1) {
    return
  }

  // 与上一层交换 zOrder
  const upperStream = sortedStreams[currentIndex + 1]
  const tempZOrder = stream.zOrder
  stream.zOrder = upperStream.zOrder
  upperStream.zOrder = tempZOrder

  applyLayout()
  
  console.log(`流 "${stream.name}" 上移一层，层级：${stream.zOrder}`)
}

const moveDown = (streamId) => {
  const stream = streams.get(streamId)
  if (!stream) return

  // 获取所有流并按 zOrder 排序
  const sortedStreams = Array.from(streams.values()).sort((a, b) => a.zOrder - b.zOrder)
  
  // 找到当前流的索引
  const currentIndex = sortedStreams.findIndex(s => s.id === streamId)
  
  // 如果已经是最下层，不能再下移
  if (currentIndex === 0) {
    return
  }

  // 与下一层交换 zOrder
  const lowerStream = sortedStreams[currentIndex - 1]
  const tempZOrder = stream.zOrder
  stream.zOrder = lowerStream.zOrder
  lowerStream.zOrder = tempZOrder

  applyLayout()
  
  console.log(`流 "${stream.name}" 下移一层，层级：${stream.zOrder}`)
}

const handleStartPush = async () => {
  const success = await startPush(pushUrl.value)
  if (success) {
    alert('✅ 推流已启动！')
  } else {
    alert('❌ 推流失败，请检查配置')
  }
}

const handleStopPush = () => {
  stopPush()
  alert('推流已停止')
}

const handleStartPlay = async () => {
  const success = await startPlay(playUrl.value)
  if (!success) {
    alert('❌ 播放失败')
  }
}

const handleStopPlay = () => {
  stopPlay()
}

// 拖拽功能
const onStreamMouseDown = (e, streamId) => {
  if (e.target.classList.contains('close-btn') || e.target.classList.contains('resize-handle')) {
    return
  }

  isDragging.value = true
  dragStreamId.value = streamId
  dragStartX.value = e.clientX
  dragStartY.value = e.clientY
  selectedStreamId.value = streamId

  e.preventDefault()
}

const onResizeMouseDown = (e, streamId) => {
  isResizing.value = true
  dragStreamId.value = streamId
  dragStartX.value = e.clientX
  dragStartY.value = e.clientY
  selectedStreamId.value = streamId

  e.stopPropagation()
  e.preventDefault()
}

const onMouseMove = (e) => {
  if (!isDragging.value && !isResizing.value) return

  const stream = streams.get(dragStreamId.value)
  if (!stream) return

  const displayDeltaX = e.clientX - dragStartX.value
  const displayDeltaY = e.clientY - dragStartY.value

  const mixDeltaX = displayDeltaX / scaleX.value
  const mixDeltaY = displayDeltaY / scaleY.value

  if (isDragging.value) {
    if (stream.type === 'screen') {
      stream.x = stream.x + mixDeltaX
      stream.y = stream.y + mixDeltaY
    } else {
      stream.x = Math.max(0, Math.min(canvasWidth.value - stream.width, stream.x + mixDeltaX))
      stream.y = Math.max(0, Math.min(canvasHeight.value - stream.height, stream.y + mixDeltaY))
    }
  } else if (isResizing.value) {
    stream.width = Math.max(50, stream.width + mixDeltaX)
    stream.height = Math.max(50, stream.height + mixDeltaY)

    if (stream.type !== 'screen') {
      stream.width = Math.min(canvasWidth.value - stream.x, stream.width)
      stream.height = Math.min(canvasHeight.value - stream.y, stream.height)
    }
  }

  dragStartX.value = e.clientX
  dragStartY.value = e.clientY

  applyLayout()
}

const onMouseUp = () => {
  if (isDragging.value || isResizing.value) {
    applyLayout()
  }
  isDragging.value = false
  isResizing.value = false
  dragStreamId.value = null
}

// 生命周期
onMounted(async () => {
  try {
    const success = await init()
    
    // 隐藏加载提示
    isInitializing.value = false

    if (!success) {
      alert('❌ 初始化失败\n\n可能原因：\n1. 腾讯云 SDK 加载失败\n2. 网络连接问题\n\n请刷新页面重试')
      return
    }

    nextTick(() => {
      calculateScale()
    })

    window.addEventListener('resize', calculateScale)
    document.addEventListener('mousemove', onMouseMove)
    document.addEventListener('mouseup', onMouseUp)
  } catch (error) {
    console.error('初始化异常:', error)
    isInitializing.value = false
    alert('❌ 初始化异常：' + error.message)
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', calculateScale)
  document.removeEventListener('mousemove', onMouseMove)
  document.removeEventListener('mouseup', onMouseUp)
  
  stopPush()
  stopPlay()
})
</script>

<style scoped>
* {
  box-sizing: border-box;
}

/* 加载遮罩 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
  color: white;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.loading-hint {
  font-size: 14px;
  opacity: 0.8;
}

.container {
  max-width: 1600px;
  margin: 0 auto;
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  transition: opacity 0.3s;
}

.container.hidden {
  opacity: 0;
  pointer-events: none;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 25px 30px;
  text-align: center;
}

.header h1 {
  font-size: 28px;
  margin-bottom: 10px;
}

.header p {
  font-size: 14px;
  opacity: 0.9;
}

.content {
  display: grid;
  grid-template-columns: 280px 1fr 280px;
  gap: 15px;
  padding: 20px;
}

.left-panel,
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.middle-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-section {
  background: #f5f5f5;
  border-radius: 10px;
  padding: 20px;
  position: relative;
}

.preview-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

#preview-canvas {
  position: relative;
}

#local_video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.empty-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #666;
  text-align: center;
  pointer-events: none;
  z-index: 2;
}

.stream-box {
  position: absolute;
  border: 3px solid #667eea;
  border-radius: 8px;
  cursor: move;
  overflow: visible;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transition: border-color 0.3s;
  background: transparent;
  pointer-events: auto;
  z-index: 10;
}

.stream-box::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(102, 126, 234, 0.1);
  pointer-events: none;
  border: 1px dashed rgba(102, 126, 234, 0.3);
}

.stream-box:hover {
  border-color: #f59e0b;
}

.stream-box.selected {
  border-color: #10b981;
  box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.3);
}

.stream-box-header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 5px 10px;
  font-size: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 10;
}

.stream-box-header .name {
  font-weight: bold;
}

.stream-box-header .close-btn {
  background: #ef4444;
  border: none;
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 12px;
  line-height: 1;
}

.stream-box-header .close-btn:hover {
  background: #dc2626;
}

.resize-handle {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 20px;
  height: 20px;
  background: linear-gradient(135deg, transparent 50%, #667eea 50%);
  cursor: nwse-resize;
  z-index: 10;
}

.control-panel {
  background: #f9f9f9;
  border-radius: 10px;
  padding: 20px;
  border: 1px solid #e0e0e0;
}

.panel-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #667eea;
  display: flex;
  align-items: center;
  gap: 8px;
}

.panel-title::before {
  content: '';
  width: 4px;
  height: 18px;
  background: #667eea;
  border-radius: 2px;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.btn {
  padding: 12px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-info {
  background: #3b82f6;
  color: white;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-xs {
  padding: 4px 8px;
  font-size: 16px;
  line-height: 1;
  min-width: 32px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #555;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
}

.form-group small {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #888;
}

.info-box {
  background: #e0e7ff;
  border-left: 4px solid #667eea;
  padding: 12px;
  border-radius: 6px;
  font-size: 13px;
  color: #4338ca;
  line-height: 1.6;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: bold;
  background: #fee2e2;
  color: #991b1b;
}

.status-badge.active {
  background: #d1fae5;
  color: #065f46;
}

.stream-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 500px;
  overflow-y: auto;
}

/* 滚动条样式 */
.stream-list::-webkit-scrollbar {
  width: 6px;
}

.stream-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.stream-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.stream-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.stream-item {
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.stream-item:hover {
  border-color: #667eea;
  transform: translateX(5px);
}

.stream-item.selected {
  border-color: #10b981;
  background: #f0fdf4;
}

.stream-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.stream-item-title {
  font-weight: bold;
  font-size: 14px;
  color: #333;
}

.stream-item-badge {
  background: #667eea;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
}

.stream-item-info {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.stream-item-actions {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .left-panel,
  .right-panel {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .content {
    padding: 10px;
  }

  .container {
    border-radius: 0;
  }
}
</style>

